#include "tcp_server.h"
#include "utils.h"
#include <iostream>

namespace OHOS {
namespace DistributedHardware {
TcpServer::TcpServer()
{
    listenSock_ = INVALID_SOCKET;
}

TcpServer::~TcpServer()
{
    close(listenSock_);
}

int TcpServer::TcpServerSocket(const uint16_t port)
{
    listenSock_ = socket(AF_INET, SOCK_STREAM, 0);
    if (listenSock_ == INVALID_SOCKET) {
        std::cout << "scoket creat fail" << std::endl;
        return INVALID_SOCKET;
    }
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);
    int ret = bind(listenSock_, (struct sockaddr*)&addr, sizeof(addr));
    if (ret == -1) {
        std::cout << "bind fail" << std::endl;
        return INVALID_SOCKET;
    }
    ret = listen(listenSock_, 5);
    if (ret == -1) {
        std::cout << "listen fail" << std::endl;
        return INVALID_SOCKET;
    }
    return listenSock_ != INVALID_SOCKET;
}

bool TcpServer::Accept(TcpClient* session)
{
    struct sockaddr_in addr;
    socklen_t len = sizeof(addr);
    int acceptSock = accept(listenSock_, (struct sockaddr*)&addr, &len);
    if (acceptSock == -1) {
        return false;
    }
    session->SetSession(acceptSock);
    return true;
}
}
}
